package com.web;


import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.entity.Employee;
import com.entity.ProEmp;
import com.entity.Project;
import com.service.EmployeeService;
import com.service.ProEmpService;
import com.service.ProjectService;
import com.util.Content;

public class UpdateProject extends HttpServlet {

	
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		if ("POST".equals(request.getMethod())) {
			
			EmployeeService employeeService=new EmployeeService();
			ProjectService projectService=new ProjectService();
			ProEmpService proEmpService=new ProEmpService();
			
			String name=request.getParameter("projectName");
			String desc=request.getParameter("projectDesc");
			String admin=request.getParameter("projectAdmin");
			String p=request.getParameter("people");
			String[] ps=getName(p);
			

			name=new String(name.getBytes("ISO8859-1"),"UTF-8");
			desc=new String(desc.getBytes("ISO8859-1"),"UTF-8");
			
			name = Content.replace(name);
			desc = Content.replace(desc);
			

			name = Content.replace(name);
			desc = Content.replace(desc);
			

			if (!"".equals(name)&&!"".equals(desc)&&!"".equals(admin)) {
				Project project=(Project)projectService.getProject(request.getSession().getAttribute("id").toString());
				project.setDesc(desc);
				project.setName(name);
				
				projectService.updateProject(project);
				
				proEmpService.delByProjectId(project.getId());
				
				ProEmp proEmp=new ProEmp();
				proEmp.setEmployeeid(admin);
				proEmp.setProjectid(project.getId());
				proEmp.setRole("admin");
				
				proEmpService.add(proEmp);
				
				if (ps!=null) {
					for (int i = 0; i < ps.length; i++) {
						Employee employee=employeeService.getByName(ps[i]);
						proEmp.setEmployeeid(employee.getId());
						proEmp.setProjectid(project.getId());
						proEmp.setRole("worker");
						
						proEmpService.add(proEmp);
					}
				}
				
				
			}
			
			response.sendRedirect("projectlist.jspx");
			//request.getRequestDispatcher("WEB-INF/views/projectlist.jsp").forward(request, response);
			
		}else {
			response.sendRedirect("projectlist.jspx");
			//request.getRequestDispatcher("WEB-INF/views/projectlist.jsp").forward(request, response);
		}
		
	}

		private String[] getName(String string){
			if ("".equals(string)||string==null) {
				return null;
			}else {
				Pattern pattern=Pattern.compile(",");
				String[] strings=pattern.split(string);
				return strings;
			}
			
		}
	
}
